<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品" prop="goodsId">
        <el-select v-model="queryParams.goodsId" size="small">
          <el-option v-if="goodsInfo != null" :label="goodsInfo.goodsName" :value="goodsInfo.goodsId" />
        </el-select>
      </el-form-item>
      <el-form-item label="成色" prop="qualityId">
        <el-select v-model="queryParams.qualityId" clearable size="small">
          <el-option v-if="qualityOptions.length > 0"
            v-for="quality in qualityOptions"
            :label="quality.qualityName"
            :value="quality.qualityId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="规格" prop="specsIds">
        <el-select v-model="queryParams.specsIds" clearable size="small">
          <el-option
            v-for="specs in specsOptions"
            :label="specs.valuesName"
            :value="specs.valuesId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['share:price:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['share:price:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['share:price:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['share:price:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          size="mini"
          plain
          @click="back">返回上级</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-input
          type="number"
          placeholder="请输入加减价格"
          size="small"
          @keyup.enter.native="updatePriceByList"
          v-model="tabPrice" />
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报价编号" align="center" prop="priceId" />
      <el-table-column label="商品" align="center" prop="goodsId" :formatter="goodsFormatter" />
      <el-table-column label="规格组" align="center" prop="specsIds" :formatter.sync="valuesFormatter" />
      <el-table-column label="成色" align="center" prop="qualityId" :formatter.sync="qualityFormatter" />
      <el-table-column label="最新价格" align="center" prop="newPrice" width="160npm">
        <template slot-scope="scope">
          <el-input type="number"
            v-model="scope.row.newPrice"
            placeholder="请填写价格"
            @focus="priceFocus(scope.row)"
            @blur="priceBlur(scope.row)"
            @keyup.enter.native="updatePriceKeyDown(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="历史价格" align="center" prop="oldPrice" :show-overflow-tooltip="true" />
      <el-table-column label="排序" align="center" prop="priceSort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['share:price:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品报价对话框 -->
    <el-dialog title="根据表格更新价格" :visible.sync="open" width="80%" append-to-body>

      <input type="file" accept=".xlsx, .xls" @change="changeFile" />

      <el-table v-loading="loading" :data="updateList">
        <el-table-column label="商品" align="center" prop="goodsId" :formatter="goodsFormatter" />
        <el-table-column label="规格组" align="center" prop="specsIds" :formatter.sync="valuesFormatter" />
        <el-table-column label="成色" align="center" prop="qualityId" :formatter.sync="qualityFormatter" />
        <el-table-column label="最新价格" align="center" prop="newPrice" />
        <el-table-column label="历史价格" align="center" prop="oldPrice" :show-overflow-tooltip="true" />
        <el-table-column label="是否匹配" align="center" prop="hasMate">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.hasMate === 1">未匹配</el-tag>
            <el-tag v-else-if="scope.row.hasMate === 2">已修改</el-tag>
            <el-tag type="success" v-else>已匹配</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!--<div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import { listPrice, getPrice, delPrice, addPrice, updatePrice, exportPrice } from "@/api/share/price";
import {getShareGoods} from "@/api/share/goods"
import {listQuality} from "@/api/share/quality"
import {listValues} from "@/api/share/values"
import {strTranArray} from "@/utils/tran/shareUtils"
import XLSX from 'xlsx'

export default {
  name: "Price",
  components: {
  },
  data() {
    return {
      tabPrice: null,
      /*修改列表*/
      updateList: [],
      /*临时存放价格*/
      oldPrice: null,
      //规格选项
      specsOptions: [],
      // 规格内容
      valuesList: [],
      // 成色列表
      qualityOptions: [],
      // 对应的商品信息
      goodsInfo: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品报价表格数据
      priceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        specsIds: null,
        qualityId: null,
        newPrice: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    const goodsId = this.$route.params && this.$route.params.goodsId;
    this.queryParams.goodsId = parseInt(goodsId);
    getShareGoods(goodsId).then(resp => {
      this.goodsInfo = resp.data;
      this.getQualityList();
      this.getSpecsOptions();
    })
    this.getList();
  },
  methods: {
    updatePriceByList() {
      if(this.tabPrice == null) {
        return
      }
      if(Number(this.tabPrice) === 0) {
        return;
      }
      this.priceList.forEach(p => {
        p.newPrice = p.newPrice == null ? 0 : p.newPrice;
        p.newPrice = Number(p.newPrice) +  Number(this.tabPrice);
        this.updatePriceKeyDown(p);
      })
      this.getList();
    },
    /*文件匹配*/
    changeFile(ev) {
      const _this = this;
      let f = ev.target.files[0];
      if(f == null) {
        return
      }
      let reader = new FileReader();
      reader.onload = function (e) {
        let data = e.target.result;
        let wb = XLSX.read(data, {type: "array"});
        let sheetNames = wb.SheetNames; //工作表名称合集
        let workSheet = wb.Sheets[sheetNames[0]]; //第一个
        let json = XLSX.utils.sheet_to_json(workSheet);
        _this.oldDataModelList(json);
      }
      reader.readAsArrayBuffer(f);
    },
    //旧系统模板匹配
    async oldDataModelList(list) {
      const goodsName = this.goodsInfo.goodsName;
      let oldName = false;
      //匹配数据
      let mateList = [];
      for(let i = 0; i < list.length; i++) {
        if(goodsName === list[i]['型号名称']) {
          oldName = true;
        }
        if(!oldName) {
          continue;
        }
        if(list[i]['型号名称'] != null && list[i]['型号名称'] !== "") {
          if(goodsName !== list[i]['型号名称']) {
            break
          }
        }
        mateList.push(list[i]);
      }
      this.msgSuccess("匹配到数据" + mateList.length + "条，正在修改数据！");
      /*匹配修改价格*/
      for(let j = 0; j < mateList.length; j++) {
        let specs1 = this.specsNameTranId(mateList[j]['规格1'].trim().replace(' ', "+"));
        let specs2 = this.specsNameTranId(mateList[j]['规格2']);
        let specsStr = specs1 + "";
        if(specs2 != null){
          specsStr = parseInt(specs1) > parseInt(specs2) ? specs2 + "," + specs1 : specs1 + "," + specs2;
        }
        for(let m = 0; m < this.updateList.length; m++) {
          if(specsStr === this.updateList[m].specsIds) {
            let price = 0;
            switch (this.updateList[m].qualityId) {
              case 1 : price = parseInt(mateList[j]['充新']);break;
              case 2 : price = parseInt(mateList[j]['靓机']);break;
              case 3 : price = parseInt(mateList[j]['屏靓壳小磕']);break;
              case 4 : price = parseInt(mateList[j]['屏细微壳小磕']);break;
              case 5 : price = parseInt(mateList[j]['小花机']);break;
              case 6 : price = parseInt(mateList[j]['花机']);break;
              case 7 : price = parseInt(mateList[j]['大花机']);break;
              case 8 : price = parseInt(mateList[j]['外爆']);break;
              case 9 : price = parseInt(mateList[j]['屏坏可测功能']);break;
            }
            //价格没变的，设置为已匹配
            if(this.updateList[m].newPrice === price) {
              this.updateList[m].hasMate = 3;
              continue;
            }
            //价格有变动,修改
            this.updateList[m].newPrice = price;
            await this.updatePriceKeyDown(this.updateList[m]);
            this.updateList[m].hasMate = 2;
          }
        }
      }
    },
    /* 规格文字转换 为id*/
    specsNameTranId(specsName) {
      for(let i = 0; i < this.specsOptions.length; i++) {
        if(this.specsOptions[i].valuesName === specsName) {
          return this.specsOptions[i].valuesId;
        }
      }
      return null;
    },
    /*返回上级*/
    back() {
      this.$router.go(-1)
    },
    /*价格框 获得光标*/
    priceFocus(row) {
      this.oldPrice = row.newPrice;
      row.newPrice = 0;
    },
    /*价格框 失去光标*/
    priceBlur(row) {
      /* 价格有变化并且不为空*/
      if(row.newPrice !== 0) {
        this.updatePriceKeyDown(row);
        return
      }
      row.newPrice = this.oldPrice;
      this.oldPrice = null;
    },
    /** 获取规格内容列表 */
    getSpecsOptions() {
      let arr = JSON.parse(this.goodsInfo.specsMap);
      let values = [];
      for(let i = 0; i < arr.length; i++) {
        values.push(arr[i][1]);
      }
      let query = {
        params : {
          valuesId : values
        }
      }
      listValues(query).then(resp => {
        this.specsOptions = resp.rows;
      })
    },
    /** 商品规格转换 */
    goodsFormatter(row){
      if(this.goodsInfo != null) {
        return this.goodsInfo.goodsName;
      }
    },
    /** 价格更新 */
    updatePriceKeyDown(row) {
      updatePrice(row).then(resp => {
        this.msgSuccess("修改成功！");
      })
    },
    /** 规格内容数据转换 */
    valuesFormatter(row){
      let arr = strTranArray(row.specsIds);
      let str = "";
      for(let i = 0; i < arr.length; i++) {

        for(let j = 0; j < this.specsOptions.length; j++) {
          if(arr[i] === this.specsOptions[j].valuesId) {
            str += "[" + this.specsOptions[j].valuesName + "] ";
            break;
          }
        }
      }
      return str.substring(0, str.length - 1);
    },
    /** 格式转换 */
    qualityFormatter(row) {
      for(let i = 0; i < this.qualityOptions.length; i++) {
        if(row.qualityId === this.qualityOptions[i].qualityId) {
          return this.qualityOptions[i].qualityName;
        }
      }
    },
    /** 查询商品所有的成色 */
    getQualityList() {
      let query = {
        params : {qualityIds: this.goodsInfo.qualityIds}
      }
      listQuality(query).then(resp => {
        this.qualityOptions = resp.rows;
      })
    },
    /** 查询商品报价列表 */
    getList() {
      this.loading = true;
      listPrice(this.queryParams).then(response => {
        this.priceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        priceId: null,
        goodsId: null,
        specsIds: null,
        qualityId: null,
        newPrice: null,
        oldPrice: null,
        priceSort: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.goodsId = this.goodsInfo.goodsId;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.priceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const _this = this;
      this.$confirm('系统将根据商品的规格和成色自动更新未添加的数据', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return addPrice(_this.goodsInfo)
      }).then(response => {
        this.msgSuccess("更新成功！")
        this.getList();
      })
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.open = true;
      listPrice({goodsId: this.queryParams.goodsId}).then(resp => {
        this.updateList = resp.rows;
        for(let i = 0; i < this.updateList.length; i++) {
          this.$set(this.updateList[i], 'hasMate', 1);
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.priceId != null) {
            updatePrice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const priceIds = row.priceId || this.ids;
      this.$confirm('是否确认删除商品报价编号为"' + priceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPrice(priceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品报价数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPrice(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
